package com.example.security.filter;

import com.example.security.bean.BeanConfig;
import com.example.security.bean.LoginUser;
import com.example.security.config.JwtUtil;
import com.example.security.exception.TokenIsExpiredException;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证拦截器
 */
public class MyAuthenticationFilter extends BasicAuthenticationFilter {

    private UserDetailsService userDetailsService;

    public MyAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    public MyAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager, authenticationEntryPoint);
    }


    public MyAuthenticationFilter(AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
        super(authenticationManager);
        this.userDetailsService=userDetailsService;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(BeanConfig.getAuthorization());
        if(token!=null){
//            if (token == null) {
////            log.warn("请登录访问");
////            throw new NoneTokenException(AuthErrorEnum.TOKEN_NEEDED.getMessage());
//            }
//        if (!token.startsWith("")) {
//            throw new IllegalTokenAuthenticationException("");
//        }
            Claims claims = JwtUtil.getClaim(token);
            if (claims == null) {
                throw new TokenIsExpiredException("");
            }
            String userName = claims.getSubject();
            if (userName == null) {
                throw new TokenIsExpiredException("");
            }
//        Date expiredTime = claims.getExpiration();
//        if ((new Date().getTime() > expiredTime.getTime())) {
////            log.warn("当前token信息已过期,请重新登录");
//            throw new TokenIsExpiredException("");
//        }
            if (userName != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                LoginUser userDetails =(LoginUser) userDetailsService.loadUserByUsername(userName);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//            log.info("用户：{}，正在访问：{}", userName, request.getRequestURI());
                logger.info("authenticated user " + userName + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }



}
